package com.mall.common.service.impl;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

import javax.annotation.Resource;

import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.mall.common.bean.Order;
import com.mall.common.bean.Pager;
import com.mall.common.bean.Pager.OrderType;
import com.mall.common.dao.TemplateDao;
import com.mall.common.domain.content.TemplateDomain;
import com.mall.common.enums.TemplateType;
import com.mall.common.hibernate.Finder;
import com.mall.common.service.TemplateService;
import com.mall.common.util.AppContext;

/**
 * Service实现类 - 邮件模板
 * author fangchen 2013-04-26
 */
@Service
@Transactional
public class TemplateServiceImpl extends BaseServiceImpl<TemplateDomain, Long> implements
		TemplateService {
	
	@Resource
	public void setBaseDao(TemplateDao templeDao) {
		super.setBaseDao(templeDao);
	}

	@Override
	@Transactional(readOnly=true)
	public Pager queryByType(Pager pager, TemplateType type, String orderBy,
			OrderType orderType) {
		Finder f = Finder.create("from TemplateDomain bean where bean.type=:type");
    	f.setParam("type", type);
    	if(OrderType.asc == orderType){
    		f.setOrder(Order.asc(orderBy));
    	}else{
    		f.setOrder(Order.desc(orderBy));
    	}
    	pager = findByPager(pager, f);
		return pager;
	}

	@Transactional(readOnly=true)
	@Cacheable(value="template", key="'template'+#templateName")
	public String getTemplatePathByName(String templateName){
		TemplateDomain template = get("name", templateName);
		if(template == null){
			return null;
		}
		return template.getPath();
	}

	@Override
	@CacheEvict(value="template",allEntries=true)
	@Transactional(propagation=Propagation.REQUIRED)
	public String save(Long id, TemplateType type, String detail) throws IOException {
		TemplateDomain template = find(id);
		if(template == null){
			return "模板不存在";
		}
		if(template.getType() == null || template.getType() != type){
			return "模板不存在";
		}
		FileOutputStream fos = new FileOutputStream(AppContext.getAppRealPath("/WEB-INF/template/"+template.getPath()));
        OutputStreamWriter osw = new OutputStreamWriter(fos,"utf-8");
        osw.write(detail);
        osw.flush(); 
		if(osw != null){
			osw.close();
		}
		if(fos != null){
			fos.close();
		}
		return null;
	}
}
